package _30define;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Authorize {
    String role();
}
class Services{
    @Authorize(role = "admin")
    public void deleteData(){
        System.out.println("允许对数据进行操作");
    }
    @Authorize(role = "user")
    public void viewData(){
        System.out.println("仅允许浏览");

    }
}
class AuthorizationTest{
    public static void executeMethod(String methodName, String userRole) {
        Services services = new Services();
        if (user(methodName, userRole)) {
            try {
                switch (methodName) {
                    case "deleteData":
                        services.deleteData ();
                        break;
                    case "viewData":
                        services.viewData ();
                        break;
                    default:
                        throw new IllegalArgumentException("无效的方法名");
                }
            } catch (Exception e) {
                e.printStackTrace ();
            }
        } else {
            System.out.println ("没有权限");
        }
    }
    private static boolean user(String methodName, String userRole) {
        if(methodName.equals("deleteData")||methodName.equals("viewData")){
          return true;
        }else return false;
    }

    public static void main(String[] args) {
        executeMethod("deleteData", "admin");
        executeMethod("viewData", "user");
        executeMethod("deleteData", "user");
        executeMethod("xxx", "admin");
    }
}
